package model.trader.trade;

import java.util.ArrayList;
import java.util.List;

import model.market.MarketInformation;
import model.market.Position;
import model.market.Trade;
import model.trader.TradeInstruction;
import model.trader.Trader;
import model.trader.TradeInstruction.IndicativePricePair;

/**
 * AMCOMMENT here.
 * @author andy
 *
 */
//AMLOW: dont need to just draw between here and hold.. can market make either side too?
public class DemandCurveTradeStructurer {

	public List<Trade> determineTrades(Trader trader,Position pos,TradeInstruction demandCurve, MarketInformation marketInfo){
		List<Trade> ret = new ArrayList<Trade>();
		if(pos.getExecutedQuantity(demandCurve.getAsset())<0){
			//MArket order to make sure we get back to zero.
			Trade closeMistake = new Trade(trader,demandCurve.getAsset(),-(pos.getExecutedQuantity(demandCurve.getAsset())));
			ret.add(closeMistake);
		}
		
		Trade directionalTrade = new Trade(trader,demandCurve.getAsset(),
											demandCurve.getNumberToTrade());
		ret.add(directionalTrade);
		//System.out.println("   Directional "+directionalTrade);
		List<IndicativePricePair> additional = demandCurve.getAdditional();
		int demandAtCurrentSimPrice = demandCurve.getNumberToTrade();
		int demandAtMarketPrice =demandCurve.getNumberToTrade();
		int totalCancelled = 0;
		for(IndicativePricePair pair:additional){
			//AM: these sorts of issues can occur due to the fuzzy nature of the evolved solutions.
			if(demandAtMarketPrice<0&&demandAtCurrentSimPrice>0||
					demandAtMarketPrice>0&&demandAtCurrentSimPrice<0
					||
					demandAtMarketPrice<0&&pair.getTrade()>0||//AMLOW: whats going on..look harder for reason negatve holdings are coming through.
					demandAtMarketPrice>0&&pair.getTrade()<0){
				Trade compensate = new Trade(trader,demandCurve.getAsset(),-(demandCurve.getNumberToTrade()-totalCancelled),pair.getPrice());
				ret.add(compensate);
				break;
			}
			
			//AM: these sorts of issues can occur due to the fuzzy nature of the evolved solutions.
			if(demandAtMarketPrice<0&&demandAtCurrentSimPrice>pair.getTrade()||
					demandAtMarketPrice>0&&demandAtCurrentSimPrice<pair.getTrade()){
				continue;
			}
			
			int tradeNumber = (demandAtCurrentSimPrice-pair.getTrade());
			totalCancelled+=tradeNumber;
			Trade compensate = new Trade(trader,demandCurve.getAsset(),-tradeNumber,pair.getPrice());
			//System.out.println(compensate+"    "+total);
			demandAtCurrentSimPrice=(pair.getTrade());
			ret.add(compensate);
		}
		
		return ret;
		
	}
}
